package com.sky.service.admin.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.admin.DishFlavorMapper;
import com.sky.mapper.admin.DishMapper;
import com.sky.mapper.admin.SetmealDishMapper;
import com.sky.pojo.Dish;
import com.sky.pojo.DishFlavor;
import com.sky.result.PageResult;
import com.sky.service.admin.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @version: 1.0
 * @Author: 李佳毅
 * @description:
 * @date: 2025-07-06 21:37
 */

@Slf4j
@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    //自动注入SetmealDishMapper对象
    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveWithFlavor(DishDTO dishDTO) {
        //复制属性
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        log.info("dish:{}", dish);
        //向数据库中插入菜品数据
        int row = dishMapper.insert(dish);
        //获取id
        Long dishId = dish.getId();
        //得到菜品喜好的集合
        List<DishFlavor> flavors = dishDTO.getFlavors();
        //遍历集合
        if (!CollectionUtils.isEmpty(flavors)) {//判断集合是否为空
            flavors.forEach(flavor -> flavor.setDishId(dishId));
            //插入菜品口味数据
            dishFlavorMapper.insertBatch(flavors);
        }
        return row > 0;
    }

    @Override
    public PageResult findDishByPage(DishPageQueryDTO dishPageQueryDTO) {
        //开启分页
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        //按照添加查询菜品数据
        List<DishVO> dishList = dishMapper.selectDishByPage(dishPageQueryDTO);
        //向下转型，用于封装数据
        Page<DishVO> p = (Page<DishVO>) dishList;
        return new PageResult(p.getTotal(), p.getResult());
    }

    @Transactional(rollbackFor = Exception.class)//回滚
    @Override
    public boolean deleteByIds(List<Long> ids) {
        /**
         * 1.判断菜品是否起售
         * 2.判断菜品是否关联了套餐
         * 3.删除菜品
         * 4.删除菜品口味
         */
        int row1 = dishMapper.selectCountByIdsAndStatus(ids, StatusConstant.ENABLE);
        if (row1 > 0) {
            throw new DeletionNotAllowedException("菜品起售中，不能删除");
        }
        //TODO  判断菜品是否关联了套餐
        int row2 = setmealDishMapper.selectCountByDishIds(ids);
        if (row2 > 0) {
            throw new DeletionNotAllowedException("菜品关联了套餐，不能删除");
        }
        //根据id删除菜品数据
        int row3 = dishMapper.deleteByIds(ids);
        //删除菜品口味数据
        //先根据id查询出菜品的口味数据
        List<DishFlavor> dishFlavors = dishFlavorMapper.selectByDishIds(ids);
        if (!CollectionUtils.isEmpty(dishFlavors)) {//判断集合是否为空,如果不为空,执行删除菜品口味数据
            dishFlavorMapper.deleteByDishIds(ids);
        }
        return row3 > 0;
    }

    @Override
    public DishVO findById(Long dishId) {
        /**
         * 1.查询菜品数据
         * 2.查询菜品的口味数据
         * 3.组装数据并返回
         */
        Dish dish = dishMapper.selectById(dishId);
        //这里用集合封装,可以复用selectByDishIds方法
        List<Long> id = new ArrayList<>();
        id.add(dishId);
        List<DishFlavor> dishFlavors = dishFlavorMapper.selectByDishIds(id);
        //复制属性
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        //添加菜品口味数据
        if (!CollectionUtils.isEmpty(dishFlavors))//如果集合不为空,添加菜品口味数据
            dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //修改菜品数据
        int row1 = dishMapper.update(dish);
        //根据dishId删除菜品口味数据
        //先查询,再删除
        List<Long> id = new ArrayList<>();
        id.add(dishDTO.getId());
        List<DishFlavor> originalFlavors = dishFlavorMapper.selectByDishIds(id);
        if (!CollectionUtils.isEmpty(originalFlavors)) {//如果集合不为空,删除菜品口味数据
            dishFlavorMapper.deleteByDishIds(id);
        }
        List<DishFlavor> newFlavors = dishDTO.getFlavors();
        //添加新的菜品口味数据
        if (!CollectionUtils.isEmpty(newFlavors)) {
            newFlavors.forEach(flavor -> flavor.setDishId(dishDTO.getId()));
            dishFlavorMapper.insertBatch(newFlavors);
        }
        return row1 > 0;
    }

    @Override
    public boolean startOrStop(Integer status, Long id) {
        Dish dish = new Dish().builder()
                .id(id)
                .status(status)
                .build();
        int row = dishMapper.updateStatus(dish);
        return row > 0;
    }

    @Override
    public List<Dish> list(Long categoryId) {
        //查询符合分类id的菜品数据 还要符合启售状态
        Dish dish = Dish.builder()
                .categoryId(categoryId)//分类id
                .status(StatusConstant.ENABLE)//启售状态
                .build();
        List<Dish> dishList = dishMapper.list(dish);
        return dishList;
    }
}
